<template>
  <div style="padding: 10px;">
    <!-- header  -->
    <div class="header">
      <el-row>
        <el-col :span="18">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-input placeholder="请输入工程名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="formSave.status" placeholder="请选择工程状态">
                <el-option label="未绑定" value="未绑定"></el-option>
                <el-option label="监测中" value="监测中"></el-option>
                <el-option label="已结束" value="已结束"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button type="primary" @click="toAdd">录入</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- table -->
    <div class="table">
      <el-table :data="EngData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="60" align="center">
        </el-table-column>
        <!-- prop属性 表格列显示内容 -->
        <el-table-column prop="serial_number" label="编号" width="120" align="center">
        </el-table-column>
        <el-table-column prop="name" label="工程名称" width="400" align="center">
        </el-table-column>
        <el-table-column prop="type" label="工程类型" align="center">
          <template v-slot="scope">
            <el-tag v-if="scope.row.type == '事业单位'" type="primary" effect="dark">事件单位</el-tag>
            <el-tag v-else-if="scope.row.type == '园区'" type="success" effect="dark">园区</el-tag>
            <el-tag v-else-if="scope.row.type == '写字楼'" type="warning" effect="dark">写字楼</el-tag>
            <el-tag v-else type="danger" effect="dark">建筑工地</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="开始时间" align="center">
          <template v-slot='scope'>
            {{ scope.row.create_time | fmtDate }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" align="center">
          <!-- 作用域插槽 获取当前行数据 -->
          <template v-slot="scope">
            <!-- 过滤器使用   需要处理时间  | 过滤器名称 -->
            {{ scope.row.end_time == null ? '' : moment(scope.row.end_time).format('YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status == '监测中'" type="success">{{ scope.row.status }}</el-tag>
            <el-tag v-else-if="scope.row.status == '未绑定'" type="warning">{{ scope.row.status }}</el-tag>
            <el-tag v-else type="danger">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-link :disabled="scope.row.status == '已结束' ? true : false" style="font-size: 12px;" :underline="false"
              type="primary" @click="toEdit(scope.row)">修改</el-link>
            <el-link :disabled="scope.row.status == '已结束' ? true : false" style="margin-left: 5px;font-size: 12px;"
              :underline="false" type="success" @click="toJump(scope.row)">绑定</el-link>
            <el-link :disabled="scope.row.status == '监测中' ? false : true" style="margin-left: 5px;font-size: 12px;"
              :underline="false" type="warning" @click="toFinish(scope.row.id)">结束</el-link>
            <el-link :disabled="scope.row.status == '未绑定' ? false : true" style="margin-left: 5px;font-size: 12px;"
              :underline="false" type="danger" @click="toDelete(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- pagination -->
    <div class="page" style="margin-top:10px;">
      <!-- hide-on-single-page 分页数据只有一页隐藏分页按钮 -->
      <el-pagination hide-on-single-page background @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="params.page" :page-sizes="[2, 5, 8, 10]"
        :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 抽屉 close关闭抽屉事件  -->
    <el-drawer @close="close" size="50%" :title="title" :visible.sync="visible" direction="rtl" custom-class="demo-drawer"
      ref="drawer">
      <div class="demo-drawer__content" style="padding: 10px 15px 10px 0;border-top: 1px solid #ededed;">
        {{ form }}
        <el-form :model="form" :rules="rules" ref="myForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="工程编号" :label-width="formLabelWidth" prop="serial_number">
                <el-input placeholder="请输入工程编号" clearable v-model="form.serial_number" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程名称" :label-width="formLabelWidth" prop="name">
                <el-input placeholder="请输入工程名称" clearable v-model="form.name" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程类型" :label-width="formLabelWidth" prop="type">
                <el-select clearable class="select" v-model="form.type" placeholder="请选择工程类型">
                  <el-option label="写字楼" value="写字楼"></el-option>
                  <el-option label="园区" value="园区"></el-option>
                  <el-option label="建筑工地" value="建筑工地"></el-option>
                  <el-option label="事业单位" value="事业单位"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域经理" :label-width="formLabelWidth" prop="charge_id">
                <el-select clearable class="select" v-model="form.charge_id" placeholder="请选择区域经理">
                  <el-option v-for="item in areaData" :key="item.id" :label="item.realname"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程经度" :label-width="formLabelWidth" prop="latitude">
                <el-input placeholder="请输入工程经度" clearable v-model="form.latitude" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程纬度" :label-width="formLabelWidth" prop="longitude">
                <el-input placeholder="请输入工程纬度" clearable v-model="form.longitude" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程地址" :label-width="formLabelWidth">
                <el-cascader placeholder="请选择工程地址" clearable class="select" v-model="form.address1" :options="pca"
                  :props="{ value: 'name', label: 'name' }"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址" :label-width="formLabelWidth">
                <el-input placeholder="请输入详细地址" clearable v-model="form.address" autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" :label-width="formLabelWidth">
                <el-input v-model="form.customer_name" placeholder="请输入客户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" :label-width="formLabelWidth">
                <el-input placeholder="请输入联系方式" clearable v-model="form.customer_telephone"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSubmit">确定</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>
<script>
// 引入lodash对象 _ 
import _ from 'lodash'
// 引入get请求 
import { get, del, post } from '@/utils/request'
// 引入省市区数据pca 
import pca from '@/assets/pca.json'
import moment from 'moment';
export default {
  data() {
    return {
      // 声明表单校验规则 
      rules: {
        serial_number: [
          { required: true, message: '请输入工程编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入工程名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择工程类型', trigger: 'change' }
        ],
        charge_id: [
          { required: true, message: '请选择区域经理', trigger: 'change' }
        ],
        latitude: [
          { required: true, message: '请输入纬度', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请输入经度', trigger: 'blur' }
        ]
      },
      pca,
      // table origin 表格数据源
      EngData: [],
      // 区域经理 
      areaData: [],
      // 客户数组
      cusData: [],
      formSave: {},
      // 存放分页数据
      params: {
        page: 1,
        pageSize: 5
      },
      // 数据总条数
      total: 0,
      // 抽屉标题
      title: '录入工程信息',
      // 控制抽屉显示与隐藏
      visible: false,
      // 表单对象 新增或者修改工程信息 
      form: {},
      // 标签文本宽度 表单标签域宽度 
      formLabelWidth: '120px'
    }
  },
  methods: {
    // 跳转到工程绑定设备页面
    toJump(row){
      // 路由跳转 
      this.$router.push({
        path:'/table/details',
        query:row
      })
    },
    // 关闭抽屉清空表单校验结果
    close(){
      this.$refs['myForm'].resetFields();
    },
    // 去修改 
    toEdit(row){
      this.visible = true;
      this.title = '修改工程信息';
      // 将当前行数据设置给表单对象 
      // this.form = {...row}
      let form = _.clone(row);
      // 将后端地址字符串 先转换为数组 
      let addressArray = form.address.split(' ');
      console.log(addressArray);
      // 工程地址 省市区 需要数组前三个元素 
      form.address1 = addressArray.slice(0,3);
      form.address = addressArray.slice(3).join('');
      this.form = form;
      // this.form = {...row};
    },
    // 去录入
    toAdd() {
      this.visible = true;
      this.title = '录入工程信息';
      // 清空表单 
      this.form = {};
    },
    // 保存或者更新
    toSubmit() {
      // 对表单进行校验 
      this.$refs.myForm.validate(async (valid) => {
        if (valid) {
          // 表示表单校验通过 可以发起保存或者更新请求 
          // 需要处理地址 后端需要地址字符串 '江苏省盐城市亭湖区盐城师范学院' 
          let data = _.clone(this.form);
          // 需要将数组转为字符串和address拼接到一起
          data.address = data.address1.join(' ') + ' ' + data.address;
          delete data.address1;
          let res = await post('/engineer/saveOrUpdate', data);
          this.$notify({
            title: '操作成功',
            message: res.message,
            type: 'success'
          });
          // 关闭模态框
          this.visible = false;
          // 重新载入数据
          this.getEngData();
        } else {
          // 表示表单校验未通过 
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 获取区域经理
    async getAreaData() {
      // role_id 3查询区域经理
      let res = await get('/user/pageQuery', { page: 1, pageSize: 1000, role_id: 3 });
      this.areaData = res.data.list;
    },
    // 获取客户
    // role_id 4 查询客户
    async getCusData() {
      let res = await get('/user/pageQuery', { page: 1, pageSize: 1000, role_id: 4 });
      this.cusData = res.data.list;
    },
    // 去结束 
    toFinish(id) {
      this.$confirm('此操作将结束该工程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发起结束工程请求
        let res = await get('/engineer/finish', { id: id });
        this.params.page = 1;
        // 重新载入数据
        this.getEngData();
        this.$message({
          type: 'success',
          message: res.message
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    // 去删除 
    toDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点击了确定按钮 发送删除请求 
        let res = await del('/engineer/deleteById', { id: id });
        // 删除完从第一页载入数据
        this.params.page = 1;
        // 重新载入数据
        this.getEngData();
        this.$message({
          type: 'success',
          message: res.message
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 处理每页条数改变方法 2条/页  5条/页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      // 每次分页都从第一页开始展示数据
      this.params.page = 1;
      this.params.pageSize = val;
      // 重新查询数据
      this.getEngData();
    },
    // 处理当前页码改变方法 1页---2页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.page = val;
      // 重新查询数据
      this.getEngData();
    },
    moment,
    // 封装获取工程信息方法
    async getEngData() {
      let res = await get('/engineer/pageQuery', this.params);
      console.log(res, '获取响应');
      this.EngData = res.data.list;
      this.total = res.data.total;
    }
  },
  created() {
    this.getEngData();
    this.getAreaData();
    this.getCusData();
  }

}
</script>
<style lang="scss" scoped>
.select {
  width: 299.167px;
}

// 设置抽屉底部样式
.demo-drawer__footer {
  border-top: 1px solid #ededed;
  padding-top: 10px;
  // 固定定位 
  position: fixed;
  bottom: 50px;
  width: 50%;
  text-align: center;
}
</style>